package com.polaris.live.dialog

import android.content.Context
import android.graphics.Color.parseColor
import android.view.View
import com.bumptech.glide.Glide
import com.lxj.xpopup.core.CenterPopupView
import com.lxj.xpopup.util.XPopupUtils
import com.polaris.live.R
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.constant.LiveConst.NoticeImageType.IMAGE
import com.polaris.live.databinding.DialogLiveNoticeBinding
import com.polaris.live.im.sfs.bean.live.SendLiveNoticeMessage
import com.polaris.live.im.sfs.bean.live.payload.LiveNoticePayloadBean
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.file.FileUtils.getFilePath
import com.polaris.live.utils.image.loadImage
import org.libpag.PAGScaleMode

/**
 * LiveNoticeDialog
 *
 * @author Created by 半仙 on 2023/12/8/008 9:20
 */
class LiveNoticeDialog(
    context: Context,
    private val sendLiveNoticeMessage: SendLiveNoticeMessage,
) : CenterPopupView(context) {

    private lateinit var mBinding: DialogLiveNoticeBinding
    override fun getImplLayoutId(): Int {
        return R.layout.dialog_live_notice
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogLiveNoticeBinding.bind(popupImplView)

        val payload = sendLiveNoticeMessage.payload ?: return

        val fromJson = JsonUtils.fromJson<LiveNoticePayloadBean>(payload)

        mBinding.tvTitle.setTextColor(parseColor(fromJson?.titleColor))

        if (fromJson?.titleImageType == IMAGE) {
            mBinding.ivBack.visibility = View.VISIBLE
            mBinding.pagView.visibility = View.GONE
            Glide.with(context).loadImage(sendLiveNoticeMessage.titleImage).into(mBinding.ivBack)
        } else {
            mBinding.ivBack.visibility = View.GONE
            mBinding.pagView.visibility = View.VISIBLE
            mBinding.pagView.apply {
                path = getFilePath(FileUtils.getPagFile(), sendLiveNoticeMessage.titleImage)
                setRepeatCount(-1)
                setScaleMode(PAGScaleMode.Zoom)
                play()
            }
        }

        mBinding.tvTitle.text = sendLiveNoticeMessage.title

        mBinding.tvDetail.text = sendLiveNoticeMessage.content
        mBinding.tvConfirm.text = sendLiveNoticeMessage.button
        mBinding.tvConfirm.setOnSingleClickListener {
            dismiss()
        }

    }

    override fun getMaxWidth(): Int {
        if (popupInfo == null) return 0
        return if (popupInfo.maxWidth == 0) (XPopupUtils.getAppWidth(context) * 1f).toInt() else popupInfo.maxWidth
    }
}